from settings import db
from datetime import datetime

class User(db.Model):
    """用户模型"""
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 关系映射：一个用户对应多个订单
    orders = db.relationship('Order', backref='user', lazy=True)

class Store(db.Model):
    """店铺模型"""
    __tablename__ = 'stores'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    store_name = db.Column(db.String(100), nullable=False)
    store_address = db.Column(db.String(200), nullable=False)
    
    # 关系映射：一个店铺对应多个订单
    orders = db.relationship('Order', backref='store', lazy=True)

class Product(db.Model):
    """产品（饮品）模型"""
    __tablename__ = 'products'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False)
    spec = db.Column(db.String(50), nullable=False)  # 规格（冰量/糖度）
    price = db.Column(db.Float, nullable=False)      # 单价
    image_path = db.Column(db.String(100), nullable=False)  # 图片路径
    
    # 关系映射：一个产品对应多个订单项
    order_items = db.relationship('OrderItem', backref='product', lazy=True)

class Order(db.Model):
    """订单模型"""
    __tablename__ = 'orders'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    order_id = db.Column(db.String(50), nullable=False, unique=True)  # 订单编号
    order_time = db.Column(db.DateTime, nullable=False)  # 下单时间
    pickup_number = db.Column(db.String(20), nullable=False)  # 取餐号
    payment_method = db.Column(db.String(50), nullable=False)  # 支付方式
    dining_type = db.Column(db.String(20), nullable=False)  # 用餐方式（堂食/外卖）
    dining_time = db.Column(db.String(50), nullable=False)  # 就餐时间
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)  # 关联用户
    store_id = db.Column(db.Integer, db.ForeignKey('stores.id'), nullable=False)  # 关联店铺
    
    # 关系映射：一个订单对应多个订单项
    items = db.relationship('OrderItem', backref='order', lazy=True, cascade='all, delete-orphan')

class OrderItem(db.Model):
    """订单项模型"""
    __tablename__ = 'order_items'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    order_id = db.Column(db.Integer, db.ForeignKey('orders.id'), nullable=False)  # 关联订单
    product_id = db.Column(db.Integer, db.ForeignKey('products.id'), nullable=False)  # 关联产品
    quantity = db.Column(db.Integer, nullable=False, default=1)  # 购买数量